<template>
  <el-dialog width="550px" title="支付" destroy-on-close append-to-body :visible.sync="show" :before-close="cancel">
    <div class="payAllData">
      <!-- 顶部 header -->
      <slot name="header"></slot>
      <div class="payTitle">{{ $t('支付详情') }} :</div>
      <slot name="detail" v-if="!useDefaultDetail" :detail="formData"></slot>
      <div v-if="useDefaultDetail">
        <div class="payMessage">
          <el-row :gutter="20">
            <el-col :span="12">{{ $t('付款账单数量') }} :{{ formData.payBillNum }}</el-col>
            <el-col :span="12">{{ $t('人民币') }} :{{ formData.rmbOrderAmount }} CNY</el-col>
          </el-row>

          <el-row style="margin: 5px 0" :gutter="20">
            <el-col :span="12">{{ $t('日元') }} :{{ formData.orderAmount }} JPY</el-col>
            <el-col :span="12">{{ $t('美元') }} :{{ formData.usdOrderAmount }} USD</el-col>
          </el-row>
          <el-row
            v-if="payChannelInfo.handlingFee"
            :gutter="20"
            style="margin-bottom: 10px; font-size: 15px; font-weight: bold"
          >
            <el-col :span="12">{{ $t('手续费') }} :{{ payChannelInfo.handlingFee }} JPY</el-col>
            <el-col :span="12">
              {{ $t('实际支付金额') }} : <span style="color: red">{{ payChannelInfo.orderAmount }}</span>
              JPY
            </el-col>
          </el-row>
        </div>
      </div>
      <div style="margin-bottom: 10px">线上支付:</div>
      <div class="payContent">
        <el-image
          v-for="(item, index) in payTypeList"
          :key="index"
          class="payContent-item"
          :style="{
            border: item.payChannel == selectPayChannel ? '2px solid #409eff' : '2px solid #ccc',
          }"
          @click="handlePayMethod(item)"
          :src="item.payChannelImg"
        />
      </div>
      <slot :handlePayMethod="handlePayMethod"> </slot>
      <div v-show="formData.sellerPoint" style="margin: 40px 0 0 0">
        可用积分:<strong>{{ formData.sellerPoint }}</strong>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="isPay" @click="cancel">
        {{ $t('已支付') }}
      </el-button>
      <el-button type="primary" plain @click="handleGoPay">
        {{ $t('去支付') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  calcFinallyAmount,
  payCashierConfig,
  sellerPointPay,
  toPay,
} from '@/api/distribution/sku/sellerApplicationList'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  props: {
    /**
     * 支付渠道筛选
     */
    filter: {
      type: Function,
    },
    /**
     * 是否显示默认详情
     */
    useDefaultDetail: {
      type: Boolean,
      default: () => true,
    },

    /**
     * 是否需要手续费
     */
    needFee: {
      type: Boolean,
      default: () => true,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      /**选择的支付方式 */
      selectPayChannel: '',
      payChannelInfo: {
        businessType: '',
        businessId: '',
        orderAmount: '',
        rmbOrderAmount: '',
        usdOrderAmount: '',
        attach: '',
        payBillNum: null,
        payChannel: '',
        handlingFee: '',
      },
      /**支付方式list */
      payTypeList: [],
      /**支付状态  */
      isPay: false,
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.$emit('updataPayType', '')
        this.selectPayChannel = ''
        this.isPay = false
        this.getList()
      }
    },
  },
  methods: {
    /**使用积分支付 */
    userIntegral() {
      // 判断积分是否足够
      if (+this.payChannelInfo.orderAmount > +this.formData.sellerPoint) {
        return this.$message({
          type: 'error',
          message: '积分不足!',
        })
      }
      this.payChannelInfo.handlingFee = ''
      this.$emit('updataPayType', '')
      this.selectPayChannel = ''
      let that = this
      this.$confirm(`本次支付将要扣除${this.formData.orderAmount}积分（1积分=1日元）`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)',
          })
          const payData = {
            ...this.formData,
            /**积分支付 */
            payChannel: 'pointPay',
            attach: JSON.stringify({
              ...JSON.parse(this.formData.attach),
              payChannel: 'pointPay',
            }),
          }
          console.log(`payData ==>`, JSON.parse(JSON.stringify(payData)))
          toPay(payData)
            .then((res) => {
              loading.close()
              this.isPay = true
              this.$message({
                type: 'success',
                message: '支付成功!',
              })
              this.cancel()

              // window.open(res.data.pay_url)
            })
            .catch((e) => {
              loading.close()
            })
          // sellerPointPay({
          //   id: this.formData.businessId,
          // }).then((res) => {
          //   this.$message({
          //     type: 'success',
          //     message: '支付成功!',
          //   })
          //   this.isPay = true
          //   this.$emit('update:show', false)
          //   this.$emit('getList')
          // })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          })
        })
    },
    /**
     * 去支付
     */
    handleGoPay() {
      if (this.selectPayChannel) {
        // 线下支付：现金/银行卡转账
        if (this.selectPayChannel == 'offlineCash' || this.selectPayChannel == 'offlineTransfer') {
          this.$emit('updataPayType', this.selectPayChannel)
        } else {
          /******************选择了积分支付*********************/
          if (this.selectPayChannel == 'pointPay') {
            return this.userIntegral()
          }
          /******************选择了积分支付end*********************/
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)',
          })

          let payData = {}
          /**是否需要手续费 */
          if (this.needFee) {
            payData = {
              ...this.payChannelInfo,
              attach: JSON.stringify({
                ...JSON.parse(this.payChannelInfo.attach),
                payChannel: this.selectPayChannel,
              }),
            }
          } else {
            payData = {
              ...this.formData,
              payChannel: this.selectPayChannel,
              attach: JSON.stringify({
                ...JSON.parse(this.formData.attach),
                payChannel: this.selectPayChannel,
              }),
            }
          }
          toPay(payData)
            .then((res) => {
              loading.close()
              this.isPay = true
              window.open(res.data.pay_url)
            })
            .catch((e) => {
              loading.close()
            })
        }
      } else {
        this.$message.error('请选择支付方式')
      }
    },
    /**选择支付方式 */
    handlePayMethod(pay) {
      this.selectPayChannel = pay.payChannel
      if (this.selectPayChannel !== 'offlineCash' && this.selectPayChannel !== 'offlineTransfer') {
        this.$emit('updataPayType', '')
      }
      if (this.needFee) {
        const data = { ...this.formData, payChannel: this.selectPayChannel }
        calcFinallyAmount(data).then((res) => {
          const { code, data } = res
          if (code === 200) {
            Object.assign(this.payChannelInfo, { ...data })
          }
        })
      }
    },
    getList() {
      // 获取支付方式
      payCashierConfig().then((res) => {
        if (this.filter) {
          this.payTypeList = this.filter(res.data)
        } else {
          this.payTypeList = res.data
        }
      })
    },
    /**清空手续费 */
    clearFee() {
      this.selectPayChannel = ''
      this.payChannelInfo = {
        businessType: '',
        businessId: '',
        orderAmount: '',
        rmbOrderAmount: '',
        usdOrderAmount: '',
        attach: '',
        payBillNum: null,
        payChannel: '',
        handlingFee: '',
      }
    },
    cancel() {
      this.clearFee()
      this.$emit('update:show', false)
      this.$emit('getList')
    },
  },
}
</script>
<style lang="scss" scoped>
.payMessage {
  text-align: center;
  font-size: 16px;
  color: black;
  font-weight: 700;
  margin-bottom: 10px;
}

// .payAllData {
//   // height: 250px;
// }
.payContentOffline {
  display: flex;
  & > :first-child {
    margin: 0 40px 0 30px;
  }
}
.payTitle {
  font-size: 24px;
  font-weight: 700;
  width: 100%;
  text-align: center;
  margin-bottom: 20px;

  color: black;
}

.payList {
  padding: 5px;
  cursor: pointer;
  border-radius: 10px;
  overflow: hidden;
  margin-right: 5px;
}

.payContent {
  padding: 5px 0;
  display: flex;
  align-items: center;
  overflow: auto;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 5px;
  &-item {
    width: 49.5%;
    aspect-ratio: 18/7;
    border-radius: 5px;
    cursor: pointer;
    ::v-deep img {
      object-fit: contain;
    }
  }
}

.adjustment {
  border-radius: 2px;
  padding: 4px;
  background-color: #e1eafc;
}
</style>
